// components/index_patrol/index_patrol.js
import tool from '../../modules/tool'

Component({

  /**
   * 组件的属性列表
   */
  properties: {

  },

  /**
   * 组件的初始数据
   */
  data: {
    list: [],
    size: 10,
    statusText: '',
    allowGetMore: true
  },

  /**
   * 组件的方法列表
   */
  methods: {
    async handleToTop() {
      return
      this.setData({
        allowGetMore: true,
        list: []
      })
      await this.get()
    },
    handleMore(e) {
      tool.handleShowPatrolMoreList(e.detail)
    },
    handleOpen(e) {
      tool.page.patrol.info(e.detail.id)
    },
    async get() {
      if (!this.data.allowGetMore) return
      this.setData({
        statusText: '正在获取，请稍候...'
      })
      let re = await tool.requestData('/patrol/preview', {
        size: this.data.size,
        finalId: (() => {
          if (this.data.list.length == 0) return undefined
          return this.data.list[this.data.list.length - 1].id
        })()
      }, 'get', (() => {
        if (this.data.list.length == 0) return true
        return false
      })())
      if (re.status) {
        this.setData({
          list: tool.deleteRepeatPatrolsAndSort([...this.data.list, ...re.data])
        })
        if (re.data.length == 0) {
          this.setData({
            allowGetMore: false
          })
        }
      } else {
        tool.handleShowToast(re.content, 'error')
      }
      this.setData({
        statusText: ''
      })
    }
  },

  attached() {
    this.get()
    tool.store.onChange('deletePatrol', () => {
      let t = tool.store.getItem('deletePatrol')
      this.setData({
        list: tool.deleteListLocalById(this.data.list, t.id)
      })
    })
    tool.store.onChange('updatePatrolInList', () => {
      this.setData({
        list: tool.updateListLocalByItem(this.data.list, tool.store.getItem('updatePatrolInList'))
      })
    })
  }
})